<template>
  <div class="picture-container">
    <!-- Left side tree structure -->
    <div class="tree-section">
      <el-tree ref="treeRef" :data="treeData" :props="defaultProps" @node-click="handleNodeClick" default-expand-all>
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span v-if="data.isEditing">
              <el-input v-model="data.label" size="small" @blur="finishEdit(data)" @keyup.enter="finishEdit(data)"
                v-focus />
            </span>
            <span v-else @dblclick="startEdit(data)">{{ node.label }}</span>
            <span>
              <el-button type="text" size="small" @click.stop="() => appendNode(data)">
                <el-icon>
                  <Plus />
                </el-icon>
              </el-button>
              <el-button type="text" size="small" @click.stop="() => removeNode(node, data)">
                <el-icon>
                  <Delete />
                </el-icon>
              </el-button>
            </span>
          </span>
        </template>
      </el-tree>
    </div>

    <!-- Right side content -->
    <div class="content-section" v-if="currentNode">
      <div class="content-title">
        <h2 class="titleh2">{{ currentNode.label }}</h2>
        <div>
          <el-button @click="save(section)">
            <el-icon>
              <CircleCheck />
            </el-icon>
            保存
          </el-button>
        </div>
      </div>
      <div class="listBox">
        <div v-for="(section, index) in currentNode.sections" :key="section.id" class="section-container">
          <div class="section-content">
            <!-- Image upload area -->
            <div>
              <el-upload ref="uploadRef" class="image-uploader" action="#" :show-file-list="false"
                :on-change="(file) => handleFileChange(file, section)" :before-upload="beforeUpload"
                :http-request="() => { }" drag>
                <template v-if="section.imageUrl">
                  <img :src="section.imageUrl" class="uploaded-image" />
                </template>
                <template v-else>
                  <div class="upload-placeholder">
                    <el-icon class="upload-icon">
                      <Plus />
                    </el-icon>
                    <div class="upload-subtitle">{{ section.title }}</div>
                  </div>
                </template>
              </el-upload>
            </div>

            <!-- Middle column -->
            <div class="markdown-edit-area">
              <el-input class="eltextarea" type="textarea" v-model="section.topMarkdown" :rows="3"
                placeholder="原图markdown文本" @change="saveNodeContent" />
              <el-input class="eltextarea" type="textarea" v-model="section.bottomMarkdown" :rows="3"
                placeholder="识别生成markdown文本" @change="saveNodeContent" />
            </div>

            <!-- Preview column -->
            <div class="markdown-preview-area">
              <div class="preview-box">
                <!-- <VueMathjax :formula="section.topMarkdown" /> -->
                <KatexRenderer :formula="section.topMarkdown" />
                <!-- <div v-html="renderMarkdown(section.topMarkdown)" class="markdown-preview"></div> -->
              </div>
              <div class="preview-box">
                <KatexRenderer :formula="section.bottomMarkdown" />
                <!-- <div v-html="renderMarkdown(section.bottomMarkdown)" class="markdown-preview"></div> -->
              </div>
            </div>
          </div>
          <!-- Action buttons -->
          <div class="action-buttons">
            <!-- <el-button type="primary" :loading="section.ocrLoading" @click="handleOCR(section)">
              <el-icon>
                <Document />
              </el-icon>
              OCR识别
            </el-button> -->
            <el-button type="success" :loading="section.llmLoading" @click="handleLLM(section, index)">
              <el-icon>
                <Edit />
              </el-icon>
              题干LLM优化
            </el-button>
            <el-button type="warning" :loading="section.verifyLoading" @click="handleVerify(section)">
              <el-icon>
                <CircleCheck />
              </el-icon>
              反向校验
            </el-button>
            <!-- <el-button @click="save(section)">
              <el-icon>
                <CircleCheck />
              </el-icon>
              保存
            </el-button> -->
          </div>
        </div>
      </div>
    </div>
    <div v-else class="empty-content">
      <el-empty description="请选择左侧节点" />
    </div>

    <!-- Upload dialog -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <div v-if="upload.currentSection?.selectedFile" class="upload-preview">
        <p>已选择文件: {{ upload.currentSection.selectedFile.name }}</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :loading="upload.isUploading" @click="submitUpload(upload.currentSection)">确
            定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { marked } from 'marked'


import KatexRenderer from './KatexRenderer.vue';
import { Plus, Delete, Document, Edit, CircleCheck, UploadFilled } from '@element-plus/icons-vue'
import { getToken } from '@/utils/auth'
import request from '@/utils/request'
import { message } from 'ant-design-vue'
import {
  llm,
  batchInsert,
  differ

} from '@/api/monitor/job'
// 自定义指令：自动聚焦
const vFocus = {
  mounted: (el) => el.querySelector('input').focus()
}

// 创建新的节点内容
const createNewSections = () => {
  return [
    {
      id: 1,
      title: '题干',
      imageUrl: '',
      type: 1,
      topMarkdown: '',
      bottomMarkdown: '',
      ocrLoading: false,
      llmLoading: false,
      verifyLoading: false,
      selectedFile: null
    },
    {
      id: 2,
      title: '答案',
      type: 2,
      imageUrl: '',
      topMarkdown: '',
      bottomMarkdown: '',
      ocrLoading: false,
      llmLoading: false,
      verifyLoading: false,
      selectedFile: null
    },
    {
      id: 3,
      title: '步骤',
      type: 3,
      imageUrl: '',
      topMarkdown: '',
      bottomMarkdown: '',
      ocrLoading: false,
      llmLoading: false,
      verifyLoading: false,
      selectedFile: null
    }
  ]
}

export default {
  name: 'PictureManagement',
  components: {
    Plus,
    Delete,
    Document,
    Edit,
    KatexRenderer,
    CircleCheck,
    UploadFilled
  },
  directives: {
    focus: vFocus
  },
  setup() {
    const treeRef = ref(null)
    const currentNode = ref(null)

    const treeData = ref([
      {
        id: 1,
        label: '根节点',
        children: [],
        sections: createNewSections(),
        isEditing: false,
        parentName: '',
        rootName: ''
      }
    ])

    const defaultProps = {
      children: 'children',
      label: 'label'
    }

    const uploadUrl = import.meta.env.VITE_APP_BASE_API + '/system/picture/importData'

    const uploadHeaders = {
      Authorization: 'Bearer ' + getToken()
    }

    const upload = reactive({
      open: false,
      title: '',
      currentSection: null,
      isUploading: false,
      headers: { Authorization: 'Bearer ' + getToken() }
    })

    const handleNodeClick = (data) => {
      if (data.isEditing) {
        return
      }
      currentNode.value = data
    }

    const startEdit = (data) => {
      const resetEditing = (nodes) => {
        nodes.forEach(node => {
          node.isEditing = false
          if (node.children && node.children.length > 0) {
            resetEditing(node.children)
          }
        })
      }
      resetEditing(treeData.value)

      data.isEditing = true
    }

    const finishEdit = (data) => {
      if (!data.label.trim()) {
        data.label = '新节点'
      }
      data.isEditing = false
      ElMessage.success('节点名称已更新')
    }

    const appendNode = (data) => {
      const newChild = {
        id: Date.now(),
        label: '新节点',
        children: [],
        sections: createNewSections(),
        isEditing: false,
        parentName: data.label,
        rootName: treeData.value[0].label
      }
      if (!data.children) {
        data.children = []
      }
      data.children.push(newChild)
      ElMessage.success('节点已添加')
    }

    const removeNode = (node, data) => {
      if (currentNode.value === data) {
        currentNode.value = null
      }
      const parent = node.parent
      const children = parent.data.children || parent.data
      const index = children.findIndex(d => d.id === data.id)
      children.splice(index, 1)
    }

    const handleUploadSuccess = (res, sectionId) => {
      if (!currentNode.value) return

      if (res.code === 200) {
        const section = currentNode.value.sections.find(s => s.id === sectionId)
        if (section) {
          const optimizedMarkdown = `

${res.msg}

      `;
          // section.imageUrl = 
          section.topMarkdown = optimizedMarkdown.trim();
          saveNodeContent()
          ElMessage.success('图片上传成功')
        }
      } else {
        ElMessage.error(res.msg || '上传失败')
      }
    }

    const handleUploadError = (err) => {
      console.error('上传失败:', err)
      ElMessage.error('图片上传失败，请重试')
    }

    const handleUploadProgress = (event, file) => {
      console.log('上传进度：', event.percent)
    }

    const beforeUpload = (file) => {
      const isImage = file.type.startsWith('image/')
      const isLt50M = file.size / 1024 / 1024 < 50

      if (!isImage) {
        ElMessage.error('只能上传图片文件！')
        return false
      }
      if (!isLt50M) {
        ElMessage.error('图片大小不能超过 50MB！')
        return false
      }
      return true
    }

    const renderMarkdown = (text) => {
      try {
        return text ? marked(text) : ''
      } catch (error) {
        console.error('Markdown渲染错误:', error)
        return text || ''
      }
    }

    const saveNodeContent = () => {
      console.log('保存节点内容：', currentNode.value)
    }

    // OCR识别
    const handleOCR = async (section) => {
      if (!section.imageUrl) {
        ElMessage.warning('请先上传图片')
        return
      }

      section.ocrLoading = true
      try {
        const response = await request.post('/api/ai/ocr', {
          imageUrl: section.imageUrl
        })
        if (response.code === 200) {
          section.topMarkdown = response.data.text
          ElMessage.success('OCR识别成功')
        } else {
          ElMessage.error(response.msg || 'OCR识别失败')
        }
      } catch (error) {
        console.error('OCR识别错误:', error)
        ElMessage.error('OCR识别失败，请重试')
      } finally {
        section.ocrLoading = false
      }
    }

    // 题干LLM优化
    const handleLLM = async (section, index) => {
      if (!section.topMarkdown) {
        ElMessage.warning('请先输入或识别文本')
        return
      }

      section.llmLoading = true
      try {
        // const response = await request.post('/api/llmCheck', {
        //   msg: section.topMarkdown
        //   //type: section.title
        // })
        const response = await llm({ parseContentAli: section.topMarkdown })
        if (response.code === 200) {

          console.log(currentNode.value, index);

          currentNode.value.sections[index].bottomMarkdown = response.msg

          ElMessage.success('LLM优化成功')
        } else {
          ElMessage.error(response.msg || 'LLM优化失败')
        }
      } catch (error) {
        console.error('LLM优化错误:', error)
        ElMessage.error('LLM优化失败，请重试')
      } finally {
        section.llmLoading = false
      }
    }

    // 反向校验
    const handleVerify = async (section) => {
      if (!section.topMarkdown || !section.bottomMarkdown) {
        ElMessage.warning('请确保上下文本框都有内容')
        return
      }

      section.verifyLoading = true
      try {
        const response = await differ( {
          parseContentAli: section.topMarkdown,
          parseContentAiMath: section.bottomMarkdown,
          //type: section.title
        })
        if (response.code === 200) {
          if (response.data.isValid) {
            ElMessage.success('校验通过：' + response.data.message)
          } else {
            ElMessage.warning('校验不通过：' + response.data.message)
          }
        } else {
          ElMessage.error(response.msg || '校验失败')
        }
      } catch (error) {
        console.error('校验错误:', error)
        ElMessage.error('校验失败，请重试')
      } finally {
        section.verifyLoading = false
      }
    }

    const handleFileChange = (file, section) => {
      section.selectedFile = file
      upload.currentSection = section
      upload.title = '上传图片'
      upload.open = true
    }

    const submitUpload = (section) => {
      if (!section.selectedFile) {
        ElMessage.error('请选择要上传的图片')
        return
      }
      upload.isUploading = true
      const formData = new FormData()
      formData.append('file', section.selectedFile.raw)

      request.post(uploadUrl, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          ...upload.headers
        }
      }).then(response => {
        upload.open = false
        upload.isUploading = false
        if (response.code === 200) {
          handleUploadSuccess(response, section.id)
        } else {
          handleUploadError(response) // 调用handleUploadError函数
        }
      }).catch(error => {
        upload.isUploading = false
        handleUploadError(error) // 调用handleUploadError函数
      })
    }

    const save = async (section, index) => {
      // batchInsert
      // if (!section.topMarkdown || !section.bottomMarkdown) {
      //   ElMessage.warning('请确保上下文本框都有内容')
      //   return
      // }


      // section.saveing = true
      try {
        // const response = await request.post('/api/llmCheck', {
        //   msg: section.topMarkdown
        //   //type: section.title
        // })

        let arr = currentNode.value.sections.map(item => {
          return {
            type: item.type,
            bottomMarkdown: item.bottomMarkdown,
            topMarkdown: item.topMarkdown
          }
        })
        let arrFit = arr.filter(item => {
          return item.bottomMarkdown && item.topMarkdown
        })

        if(!arrFit.length){
          return 
        }
        console.log(arrFit);

        const response = await batchInsert({
          parentName: currentNode.value.parentName, name: currentNode.value.label
          , rootName: currentNode.value.rootName, addModels: arrFit
        })
        if (response.code === 200) {

          // console.log(currentNode.value,index);

          // currentNode.value.sections[index].bottomMarkdown = response.msg

          ElMessage.success('保存成功')
        } else {
          ElMessage.error(response.msg || '保存失败')
        }
      } catch (error) {
        console.error('LLM优化错误:', error)
        ElMessage.error('保存失败，请重试')
      } finally {
        // section.saveing = false
      }
    }

    return {
      treeRef,
      treeData,
      currentNode,
      defaultProps,
      uploadUrl,
      uploadHeaders,
      handleNodeClick,
      startEdit,
      finishEdit,
      appendNode,
      removeNode,
      handleUploadSuccess,
      handleUploadError,
      handleUploadProgress,
      beforeUpload,
      renderMarkdown,
      saveNodeContent,
      handleOCR,
      handleLLM,
      handleVerify,
      handleFileChange,
      submitUpload,
      upload,
      save
    }
  }
}
</script>

<style scoped>
.picture-container {
  display: flex;
  height: 100%;
  padding: 20px;
  gap: 20px;
}

.tree-section {
  width: 250px;
  border-right: 1px solid #dcdfe6;
  padding-right: 20px;
}

.content-section {
  flex: 1;
  overflow-y: auto;
}

.empty-content {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}



.section-content {
  display: flex;
  gap: 20px;
}

.listBox {
  display: flex;
  flex-direction: column;
  height: 92vh;
}

.section-container {
  margin-bottom: 30px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 20px;
  height: 33%;
  overflow-y: auto;
  padding-bottom: 10px;
}

.upload-area {
  width: 200px;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  gap: 16px;
  text-align: center;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  width: 32px;
  height: 32px;
}

.upload-subtitle {
  font-size: 16px;
  color: #606266;
  font-weight: bold;
}

.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: border-color 0.3s;
}

.image-uploader:hover {
  border-color: #409eff;
}

.uploaded-image {
  width: 178px;
  height: 178px;
  object-fit: cover;
  display: block;
}

.el-upload {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.markdown-edit-area {
  height: 178px;
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10px;

}

.eltextarea {
  height: 84px;
}

.eltextarea>>>.el-textarea__inner {
  height: 84px;
}

.markdown-preview-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

/* .preview-box{
    height: 84px;
  } */
.preview-box {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  min-height: 84px;
  background-color: #f8f9fa;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.custom-tree-node :deep(.el-input) {
  width: 150px;
}

.markdown-preview {
  min-height: 150px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin-top: 10px;
  justify-content: center;
}

.action-buttons .el-button {
  min-width: 120px;
}

.action-buttons .el-icon {
  margin-right: 4px;
}

.content-title {
  display: flex;
  justify-content: space-between;
  margin: 0 0 20px;
  padding-bottom: 10px;

  border-bottom: 1px solid #dcdfe6;
}

.titleh2 {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}

.upload-preview {
  text-align: center;
  margin-bottom: 20px;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>